package com.pcxm.cm.util;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * @author songpengcheng
 *
 */
public class ExcelExport {
	
	/**
	 * @param list
	 *				---->报表内容，list对象
	 * @param excelHeader
	 *				---->数组，表格列名
	 * @param excelHeaderWidth
	 *				---->数组，表格列宽度
	 * @param fields
	 *				---->数组，list需要输出的字段
	 * @return
	 * 
	 * @Example
	 * HSSFWorkbook wb = export(list,new String[]{ "Sno", "Name", "Age" },new int[]{ 100, 200, 200 },new String[]{ "sno", "name", "age" });
	 * response.setContentType("application/vnd.ms-excel");
	 * response.setHeader("Content-disposition","attachment;filename=student.xls");
	 * OutputStream ouputStream = response.getOutputStream();
	 * wb.write(ouputStream);
	 * ouputStream.flush();
	 * ouputStream.close();
	 */
	public static HSSFWorkbook export(List list,String[] excelHeader,int[] excelHeaderWidth, String[] fields) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("报表信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 添加表格头
		for (int i = 0; i < excelHeader.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(excelHeader[i]);
			cell.setCellStyle(style);
		}

		// 设置列宽度（像素）
		for (int i = 0; i < excelHeaderWidth.length; i++) {
			sheet.setColumnWidth(i, 32 * excelHeaderWidth[i]);
		}
		// 添加表内容
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 1);
			Object object = list.get(i);
			for (int j = 0; j < fields.length; j++) {
				String field = fields[j];
				try {
					Class clazz = object.getClass();
					Field idField = clazz.getDeclaredField(field);
					idField.setAccessible( true );
					row.createCell(j).setCellValue(idField.get(object).toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return wb;
	}

}
